/**
 * 性能监控工具
 * 用于监控应用性能和识别瓶颈
 */

interface PerformanceEntry {
  name: string;
  startTime: number;
  endTime?: number;
  duration?: number;
}

class PerformanceMonitor {
  private entries: Map<string, PerformanceEntry> = new Map();
  private isEnabled: boolean = false;

  constructor() {
    // 在开发环境启用性能监控
    this.isEnabled = import.meta.env.DEV;
  }

  /**
   * 开始性能监控
   */
  start(name: string) {
    if (!this.isEnabled) return;

    this.entries.set(name, {
      name,
      startTime: performance.now(),
    });
  }

  /**
   * 结束性能监控
   */
  end(name: string) {
    if (!this.isEnabled) return;

    const entry = this.entries.get(name);
    if (entry) {
      entry.endTime = performance.now();
      entry.duration = entry.endTime - entry.startTime;

      // 如果耗时超过阈值，输出警告
      if (entry.duration > 16) {
        // 16ms 约等于 60fps
        console.warn(
          `🐌 性能警告: ${name} 耗时 ${entry.duration.toFixed(2)}ms`
        );
      } else if (entry.duration > 5) {
        console.log(`⚡ 性能监控: ${name} 耗时 ${entry.duration.toFixed(2)}ms`);
      }
    }
  }

  /**
   * 测量函数执行时间
   */
  measure<T>(name: string, fn: () => T): T {
    if (!this.isEnabled) return fn();

    this.start(name);
    const result = fn();
    this.end(name);
    return result;
  }

  /**
   * 测量异步函数执行时间
   */
  async measureAsync<T>(name: string, fn: () => Promise<T>): Promise<T> {
    if (!this.isEnabled) return fn();

    this.start(name);
    const result = await fn();
    this.end(name);
    return result;
  }

  /**
   * 获取所有性能条目
   */
  getEntries(): PerformanceEntry[] {
    return Array.from(this.entries.values());
  }

  /**
   * 获取性能统计
   */
  getStats() {
    const entries = this.getEntries().filter(e => e.duration !== undefined);

    if (entries.length === 0) {
      return {
        total: 0,
        average: 0,
        max: 0,
        min: 0,
        slowOperations: [],
      };
    }

    const durations = entries.map(e => e.duration!);
    const total = durations.reduce((sum, d) => sum + d, 0);
    const average = total / durations.length;
    const max = Math.max(...durations);
    const min = Math.min(...durations);
    const slowOperations = entries
      .filter(e => e.duration! > 16)
      .sort((a, b) => b.duration! - a.duration!);

    return {
      total: Number(total.toFixed(2)),
      average: Number(average.toFixed(2)),
      max: Number(max.toFixed(2)),
      min: Number(min.toFixed(2)),
      slowOperations,
    };
  }

  /**
   * 清除所有记录
   */
  clear() {
    this.entries.clear();
  }

  /**
   * 启用/禁用监控
   */
  setEnabled(enabled: boolean) {
    this.isEnabled = enabled;
  }
}

// 全局实例
export const performanceMonitor = new PerformanceMonitor();

/**
 * 性能监控装饰器
 */
export function monitor(name?: string) {
  return function (
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    const originalMethod = descriptor.value;
    const monitorName = name || `${target.constructor.name}.${propertyKey}`;

    descriptor.value = function (...args: any[]) {
      return performanceMonitor.measure(monitorName, () => {
        return originalMethod.apply(this, args);
      });
    };

    return descriptor;
  };
}

/**
 * Vue组合式函数：性能监控Hook
 */
export function usePerformanceMonitor() {
  return {
    start: (name: string) => performanceMonitor.start(name),
    end: (name: string) => performanceMonitor.end(name),
    measure: <T>(name: string, fn: () => T) =>
      performanceMonitor.measure(name, fn),
    measureAsync: <T>(name: string, fn: () => Promise<T>) =>
      performanceMonitor.measureAsync(name, fn),
    getStats: () => performanceMonitor.getStats(),
    clear: () => performanceMonitor.clear(),
  };
}
